﻿/*****************************************介绍*****************************************
 * 作者：User
 * 创建时间：2025-03-28 14:25:27
 * 功能：基础数据管理器
**************************************************************************************/

using Game.BaseData;
using Game.Framework;
using Game.Framework.Utility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

[CustomModule(11)]
public class BaseDataMgr : BaseManager<BaseDataMgr>, IModule
{
    private Config m_Cfg;
    private InitResult m_InitResult;
    private Dictionary<string, Config.Country> m_Contries;

    private BaseDataMgr() { }

    public Config Cfg => m_Cfg;

    void IModule.Init()
    {
        m_InitResult = InitResult.Wait;
        ReqConfig();
    }

    private void ReqConfig()
    {
#if UNITY_EDITOR
        string url = $"http://localhost:5556/HttpServer/journeygallery/cfgs/ios/{Application.version}/en_cfg.json";
        CommonMono.Instance.SendGetRequest<byte[]>(url, LoadSuccHandle, LoadFailHandle);
#else
        string url = GlobalFixedString.REQ_URL;
        var reqParam = new JObject()
        {
            {"country", "us"},
            {"language", TextUtil.GetLanguageShortName(Application.systemLanguage)},
            {"version", Application.version},
            {"product_name", GlobalFixedString.PRODUCT_NAME},
            {"st", DateTime.Now.ToString("yyMMddHHmmss")},
            {"is_has_sim", NativeInteraction.Instance.HasSimCard() }
        };
        var reqHeaders = new JObject()
        {
            {"Content-Type", "application/json" },
            {"Product", GlobalFixedString.PRODUCT_NAME }
        };
        var data = new CommonMono.NetPostData();
        data.url = url;
        data.reqParams = reqParam;
        data.reqHeaders = reqHeaders;
        data.callBack = LoadSuccHandle;
        data.failCallBack = LoadFailHandle;
        data.timeout = 20;
        CommonMono.Instance.SendPostReqest(data);
#endif
    }

    private void LoadFailHandle(string error)
    {
        LogManager.LogError($"请求基础数据失败，error:{error}", "BaseDataMgr");
        ReqConfig();
    }

    private void LoadSuccHandle(byte[] data)
    {
        try
        {
            string json = Encoding.UTF8.GetString(data);
            m_Cfg = JsonConvert.DeserializeObject<Config>(json);
            JObject obj = JObject.Parse(json);
            m_Cfg.Parse(obj);
            m_Contries = new Dictionary<string, Config.Country>(m_Cfg.counties.Count);
            foreach (var item in m_Cfg.counties)
                m_Contries.Add(item.name, item);

            m_InitResult.type = E_ResultType.Success;
        }
        catch (Exception e)
        {
            m_InitResult = new InitResult($"cfg解析出错，请检查！！ msg:{e.Message} stack:{e.StackTrace}", E_ResultType.Fail);
        }
    }

    public string GetLanguageValue(string key)
    {
        if (m_Cfg == null || m_Cfg.lan == null) return key;
        if (m_Cfg.lan.TryGetValue(key, out string value))
            return value;
        return key;
    }

    /// <summary>获取指定国家的基础数据</summary>
    public Config.Country GetCountryCfg(string name)
    {
        m_Contries.TryGetValue(name, out var resultl);
        return resultl;
    }

    InitResult IModule.GetInitResult()
    {
        return m_InitResult;
    }

    void IModule.Clear()
    {
        m_InitResult.type = E_ResultType.Waiting;
        m_InitResult.error = string.Empty;
        m_Cfg = null;
    }
}